package com.zyx.flowable.service.impl;

import com.zyx.flowable.domain.dto.FlowDeployProcDto;
import com.zyx.flowable.domain.vo.FlowDeployProcVO;
import com.zyx.flowable.factory.FlowServiceFactory;
import com.zyx.flowable.service.IFlowDefinitionService;
import com.zyx.wanshu.util.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>流程定义相关的Service</p>
 *
 * @author Yaxi.Zhang
 * @since 2022/8/24 00:51
 */
@Service
public class FlowDefinitionServiceImpl extends FlowServiceFactory implements IFlowDefinitionService {
    @Override
    public FlowDeployProcVO list(FlowDeployProcVO pageVo) {
        List<FlowDeployProcDto> list = new ArrayList<>();
        // 1.查询所有流程定义
        ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
        if (StringUtils.isNotBlank(pageVo.getKey())) {
            processDefinitionQuery.processDefinitionNameLike("%" + pageVo.getKey() + "%");
        }
        //查询到的分页的数据
        List<ProcessDefinition> processDefinitions = processDefinitionQuery.
                listPage(pageVo.getPageSize() * (pageVo.getCurrPage() - 1), pageVo.getPageSize());
        if (processDefinitions != null && processDefinitions.size() > 0) {
            // 说明有部署的流程
            for (ProcessDefinition processDefinition : processDefinitions) {
                FlowDeployProcDto dto = new FlowDeployProcDto();
                // 根据部署的流程ID查找对应的 流程定义信息
                Deployment deployment = repositoryService
                        .createDeploymentQuery().deploymentId(processDefinition.getDeploymentId()).singleResult();
                dto.setId(processDefinition.getId());
                dto.setName(processDefinition.getName());
                dto.setCategory(processDefinition.getCategory());
                dto.setTenantId(processDefinition.getTenantId());
                dto.setDeployId(processDefinition.getDeploymentId());
                dto.setFlowKey(processDefinition.getKey());
                dto.setDeployDate(deployment.getDeploymentTime());
                dto.setDescription(processDefinition.getDescription());
                dto.setVersion(processDefinition.getVersion());
                dto.setSuspensionState(processDefinition.isSuspended() ? 2 : 1);
                list.add(dto);
            }
        }
        pageVo.setList(list);
        pageVo.setTotalCount((int) processDefinitionQuery.count());
        // 4 / 5 1  5/5 2  6/5 2
        pageVo.setTotalPage((int) ((processDefinitionQuery.count() + 1) / pageVo.getPageSize() + 1));
        return pageVo;
    }
}
